/**
 * Moondance UML modeling tool
 * 
 * This program is free software; you can redistribute it and
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package ro.pub.cs.se.moondance.directedit;

import java.util.ArrayList;
import java.util.Arrays;

import org.eclipse.jface.viewers.ICellEditorValidator;

import ro.pub.cs.se.moondance.model.VisibilityType;

/**
 * ICellValidator to validate direct edit values in the operation label
 * Collaborates with an instance of ValidationMessageHandler
 */
public class OperationNameTypeCellEditorValidator implements
		ICellEditorValidator {

	private ValidationMessageHandler handler;
	private static String patterns[] = { "<<constructor>>", "<<destructor>>",
			"<<static>>", "<<abstract>>" };
	private ArrayList<String> patternsList;

	/**
	 * @param validationMessageHandler
	 *            the validation message handler to pass error information to
	 */
	public OperationNameTypeCellEditorValidator(
			ValidationMessageHandler validationMessageHandler) {
		this.handler = validationMessageHandler;
		patternsList = new ArrayList<String>(Arrays.asList(patterns));
	}

	/**
	 * @param validation
	 *            of attribute name
	 * @return the error message if an error has occurred, otherwise null
	 */

	// visibility <<constructor>>/<<destructor>> <<static>> <<abstract>>
	// name(parameters) : returnType
	public String isValid(Object value) {
		String string = (String) value;
		@SuppressWarnings("unused")
		String firstPart, secondPart;
		int openBracketIndex, closedBracketIndex;
		String parameters = "";
		if (string.length() == 0) {
			String text = "Operation definition should include at least name and type";
			return setMessageText(text);
		}

		int colonIndex = string.indexOf(':');
		if (colonIndex >= 0) {
			firstPart = string.substring(0, colonIndex);
			secondPart = string.substring(colonIndex + 1);
		} else {
			firstPart = string;
			secondPart = "";
		}

		openBracketIndex = firstPart.indexOf('(');
		closedBracketIndex = firstPart.indexOf(')');
		if ((openBracketIndex >= 0) && (closedBracketIndex >= 0)) {
			parameters = firstPart.substring(openBracketIndex + 1,
					closedBracketIndex);
			firstPart = firstPart.substring(0, openBracketIndex);
		}

		String[] result = firstPart.split("\\s");

		switch (result.length) {
		case 1:// visibility | pattern | name
			if ((openBracketIndex >= 0) && (closedBracketIndex >= 0))// name
				if (ForbiddenIdentifierNames.contains(result[0])) {
					String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
					return setMessageText(text);
				} else {
					if (result[0].startsWith("<<") && result[0].endsWith(">>")) {// pattern
						if (!patternsList.contains(result[0])) {
							String text = "Invalid pattern. Choose  from: "
									+ patternsList;
							return setMessageText(text);
						}
					} else {// visibility
						if (!VisibilityType.contains(result[0])) {
							String text = "Invalid visibility type. Permissible types are: "
									+ VisibilityType.getTypes();
							return setMessageText(text);
						}
					}
				}
			break;
		case 2: // visibility name || visibility pattern | pattern name |
			// pattern pattern
			if (result[0].startsWith("<<") && result[0].endsWith(">>")) {// pattern
				if (!patternsList.contains(result[0])) {
					String text = "Invalid pattern. Choose  from: "
							+ patternsList;
					return setMessageText(text);
				}

				if (result[1].startsWith("<<") && result[1].endsWith(">>")) {// second
					// pattern
					if (!patternsList.contains(result[1])) {
						String text = "Invalid pattern. Choose  from: "
								+ patternsList;
						return setMessageText(text);
					}

					if (!(result[0].equals("<<abstract>>") && result[1]
							.equals("<<destructor>>"))) {
						String text = "Invalid pattern combination. Only <<abstract>> <<destructor>> allowed";
						return setMessageText(text);
					}
				} else {// name
					if (ForbiddenIdentifierNames.contains(result[1])) {
						String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
						return setMessageText(text);
					}
				}
			} else {// visiblity
				if (!VisibilityType.contains(result[0])) {
					String text = "Invalid visibility type. Permissible types are: "
							+ VisibilityType.getTypes();
					return setMessageText(text);
				}
				if (result[1].startsWith("<<") && result[1].endsWith(">>")) {// pattern
					if (!patternsList.contains(result[1])) {
						String text = "Invalid pattern. Choose  from: "
								+ patternsList;
						return setMessageText(text);
					}
				} else {// name
					if (ForbiddenIdentifierNames.contains(result[1])) {
						String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
						return setMessageText(text);
					}
				}
			}
			break;

		case 3: // visibility pattern name | pattern pattern name
			if (result[0].startsWith("<<") && result[0].endsWith(">>")) {// pattern
				if (!patternsList.contains(result[0])) {
					String text = "Invalid pattern. Choose  from: "
							+ patternsList;
					return setMessageText(text);
				}
				if (!patternsList.contains(result[1])) {
					String text = "Invalid pattern. Choose  from: "
							+ patternsList;
					return setMessageText(text);
				}

				if (!(result[0].equals("<<abstract>>") && result[1]
						.equals("<<destructor>>"))) {
					String text = "Invalid pattern combination. Only <<abstract>> <<destructor>> allowed";
					return setMessageText(text);
				}
				if (ForbiddenIdentifierNames.contains(result[2])) {
					String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
					return setMessageText(text);
				}
			} else {// visibility
				if (!VisibilityType.contains(result[0])) {
					String text = "Invalid visibility type. Permissible types are: "
							+ VisibilityType.getTypes();
					return setMessageText(text);
				}
				if (!patternsList.contains(result[1])) {
					String text = "Invalid pattern. Choose  from: "
							+ patternsList;
					return setMessageText(text);
				}
				if (ForbiddenIdentifierNames.contains(result[2])) {
					String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
					return setMessageText(text);
				}
			}
			break;

		case 4:// visibility pattern pattern name
			if (!VisibilityType.contains(result[0])) {
				String text = "Invalid visibility type. Permissible types are: "
						+ VisibilityType.getTypes();
				return setMessageText(text);
			}
			if (!patternsList.contains(result[1])) {
				String text = "Invalid pattern. Choose  from: " + patternsList;
				return setMessageText(text);
			}
			if (!patternsList.contains(result[2])) {
				String text = "Invalid pattern. Choose  from: " + patternsList;
				return setMessageText(text);
			}

			if (!(result[1].equals("<<abstract>>") && result[2]
					.equals("<<destructor>>"))) {
				String text = "Invalid pattern combination. Only <<abstract>> <<destructor>> allowed";
				return setMessageText(text);
			}
			if (ForbiddenIdentifierNames.contains(result[3])) {
				String text = "Operation name is an invalid identifier. Do not use java keywords as attribute names.";
				return setMessageText(text);
			}
			break;

		}

		if ((openBracketIndex >= 0) && (closedBracketIndex >= 0))// parameters
			// specified
			if (parameters.length() > 0) {// name1:type1,name2:type2,...
				String[] splitParameters = parameters.split(",");
				for (int i = 0; i < splitParameters.length; i++) {
					String[] nameType = splitParameters[i].split(":");
					if (ForbiddenIdentifierNames.contains(nameType[0])) {
						String text = "Invalid parameter name. Do not use java keywords as parameter names.";
						return setMessageText(text);
					}
				}
			}

		return unsetMessageText();
	}

	private String unsetMessageText() {
		handler.reset();
		return null;
	}

	private String setMessageText(String text) {
		handler.setMessageText(text);
		return text;
	}
}
